package cn.itcast.order.service.Servicerimpe;

import cn.itcast.feign.client.ItemClient;
import cn.itcast.feign.client.UserClient;
import cn.itcast.hmall.dto.common.ResultDTO;
import cn.itcast.hmall.dto.common.ThreadLocalUtil;
import cn.itcast.hmall.dto.order.OrderReqDTO;
import cn.itcast.hmall.pojo.item.Item;
import cn.itcast.hmall.pojo.order.Order;
import cn.itcast.hmall.pojo.order.OrderDetail;
import cn.itcast.hmall.pojo.order.OrderLogistics;
import cn.itcast.hmall.pojo.user.Address;
import cn.itcast.hmall.pojo.user.User;
import cn.itcast.order.mapper.orderDetailMapper;
import cn.itcast.order.mapper.orderLogisMapper;
import cn.itcast.order.mapper.orderMapper;
import cn.itcast.order.service.ServiceOrder;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.Map;

@Service
public class ServicerOrderImpe extends ServiceImpl<orderMapper, Order> implements ServiceOrder {
    @Autowired
    ItemClient itemClient;
    @Autowired
    orderDetailMapper orderDetailMappers;
    @Autowired
    orderLogisMapper orderLogisMappers;
    @Autowired
    UserClient userClient;
    @Autowired
    orderMapper orderMappers;




    @Override
    public void createOrder(OrderReqDTO orderReqDTO) {
        //- 2）商品微服务提供FeignClient，实现根据id查询商品的接口
        //        - 3）根据itemId查询商品信息
        Item additem = itemClient.additem(orderReqDTO.getItemId() + "");
        //        - 4）基于商品价格、购买数量计算商品总价：totalFee
        Long price = additem.getPrice();
        long l = price * orderReqDTO.getNum();

        //- 6）将Order写入数据库tb_order表中
        Order order = new Order();
        //金额
        order.setTotalFee(l);
        order.setPaymentType(orderReqDTO.getPaymentType());
        order.setUserId(orderReqDTO.getAddressId());
        //        - 5）封装Order对象，初始status为  未支付
        order.setStatus(1);
        save(order);
        //  - 7）将商品信息、orderId信息封装为OrderDetail对象，写入tb_order_detail表
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setItemId(order.getId());
        orderDetail.setNum(orderReqDTO.getNum());
        orderDetail.setPrice(price);
        orderDetail.setSpec(additem.getSpec());
        orderDetail.setName(additem.getName());
        orderDetail.setImage(additem.getImage());
        orderDetail.setCreateTime(additem.getCreateTime());
        orderDetail.setUpdateTime(additem.getUpdateTime());
        orderDetailMappers.insert(orderDetail);
        //  - 8）将user微服务的`根据id查询地址`接口封装为FeignClient
        //  - 9）根据addressId查询user-service服务，获取地址信息
        Address address = userClient.selectAddress(orderReqDTO.getAddressId().toString());
        //  - 10）将地址封装为`OrderLogistics`对象，写入tb_order_logistics表(物流信息表)
        OrderLogistics orderLogistics = new OrderLogistics();
        orderLogistics.setOrderId(order.getId());
        orderLogistics.setContact(address.getContact());
        orderLogistics.setMobile(address.getMobile());
        orderLogistics.setProvince(address.getProvince());
        orderLogistics.setCity(address.getCity());
        orderLogistics.setTown(address.getTown());
        orderLogistics.setStreet(address.getStreet());
         orderLogisMappers.insert(orderLogistics);
        int i = (additem.getStock()) - (orderDetail.getNum());
        //  - 11）在item商品微服务提供减库存接口，并编写FeignClient
        //  - 12）调用item微服务的减库存接口

        if (i > 0) {
            additem.setStock(i);
           itemClient.resultDTO(additem);
        }

    }

    @Override
    public ResultDTO payorders(long orderid, Map<String, String> key) {
        //- 根据订单id查询订单信息
        Order order = orderMappers.selectById(orderid);
        //- 检查订单状态是否为 1 (待支付)      如果为1继续    如果为其它状态结束请求
        Long userId = ThreadLocalUtil.getUserId();
        if (order.getStatus() == 1) {
            //- 获取当前登录用户id, 使用feign查询用户信息
            User user = userClient.userselect(userId);
            String password = key.get("password");
            //- 判断输入的密码是否正确:   密码使用md5加密
            if (user.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8)))) {
                user.setBalance(user.getBalance()-order.getTotalFee());
                //修改用户

                userClient.updateUserById(user);
                //把订单状态改为已支付
                order.setStatus(2);
                orderMappers.updateById(order);
                return ResultDTO.ok();
            }


        }
        return ResultDTO.error();
    }


}
